package com.llpy.controller;

import com.llpy.Service.ImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
public class ImgController {
    @Autowired
    private ImgService imgService;

    //保存图片
    @PostMapping("/saveImg")
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
        // 将文件存储到 MongoDB GridFS 中
        return imgService.saveImage(file).toHexString();
    }

    @GetMapping("/getImg/{fileId}")
    public ResponseEntity<byte[]> down(@PathVariable String fileId) throws Exception {
        // 创建要写入的输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        imgService.getImage(fileId,outputStream);
        byte[] imageBinaryData = outputStream.toByteArray();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<>(imageBinaryData, headers, HttpStatus.OK);
    }
}
